<?php

class FoodController extends Zend_Controller_Action {

    const BASE_URL = "http://food.apps.zing.vn/";

    private static $query_cache;

    public function checkAccessKeyParams() {
        $appid = $this->_request->getParam("key");
        $sig = $this->_request->getParam("sig");
        $method = $this->_request->getParam("method");
        if ($appid == "" || $sig == "" || $method == "") {
            echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$INVAILD_PARAMS);
            return false;
        } else {
            if ($appid != Haibl_ConfigData::FOOD_KEY) {
                echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                return false;
            } else {
                $params = $this->_request->getParams();
                $requestParams = '';
                foreach ($params as $key => $value) {
                    if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                        $requestParams.= $key . '=' . $value;
                    }
                }
                $requestParams.= Haibl_ConfigData::ACCESS_KEY;
                $encryptParams = md5($requestParams);

                if ($encryptParams == $sig) {
                    return true;
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                    if (Haibl_ConfigData::DEBUG) {
                        echo "<p>requestParams = " . $requestParams . "</p>";
                        echo "<p>encryptParams = " . $encryptParams . "</p>";
                    }
                    return false;
                }
            }
        }
    }

    public function __construct(\Zend_Controller_Request_Abstract $request, \Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) {
        parent::__construct($request, $response, $invokeArgs);
        $frontendoptions = array(
            'lifetime' => 60 * 60 * 24, // 1 days
            'automatic_serialization' => true
        );
        $backendoptions = array(
            'cache_dir' => CACHED_PATH,
            'file_name_prefix' => 'zend_cache_query_food',
            'hashed_directory_level' => 2
        );
        self::$query_cache = Zend_Cache::factory('Core', 'File', $frontendoptions, $backendoptions);
    }

    public function getAccessMemcachedKey() {
        $params = $this->_request->getParams();
        $requestParams = '';
        foreach ($params as $key => $value) {
            if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                $requestParams.= $key . '=' . $value;
            }
        }
        $action = $this->_request->getActionName();
        return md5($action . $requestParams);
    }

    public function getImageRealPath($imagePath) {
        if (strpos($imagePath, "(")) {
            $rs = explode("(", $imagePath);
            if (strpos($rs[1], ")")) {
                $rs = explode(")", $rs[1]);
                return $rs[0];
            }
            return $imagePath;
        } else {
            return $imagePath;
        }
    }

    public function indexAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $isAccess = $this->checkAccessKeyParams();
        if ($isAccess) {

            $method = $this->_request->getParam("method") == "" ? "new" : $this->_request->getParam("method");
            $page = $this->_request->getParam("page") == "" ? 1 : $this->_request->getParam("page");
            $type = $this->_request->getParam("type") == "" ? 1 : $this->_request->getParam("type");

            $key = $this->getAccessMemcachedKey();
            $memCachedData = null; // self::$memcache->get($key);
            if ($memCachedData != null) {
                echo json_encode($memCachedData);
            } else {
                $lists = null;
                if ($method == "getList") {
                    //lay danh sach cac chuyen muc
                    //http://localhost/public/food?method=getList&type=local&page=1&count=50&key=2861010&sig=0b32d77781f90b7e267ff109be020786
                    //http://localhost/public/food?method=getList&type=cate&page=1&count=50&key=2861010&sig=74d12cca484015b4642320bf8715747c
                    $lists = $this->getList(static::BASE_URL);
                    if ($type == 'cate') {
                        $lists = $lists['cate'];
                    } else if ($type == 'local') {
                        $lists = $lists['local'];
                    }
                } else if ($method == "getDetail") {
                    //http://localhost/public/food?method=getDetail&id=fnb/local/id/5&page=1&count=50&key=2861010&sig=f507075cd1bf2f964445aae8f70e37fb
                    //http://localhost/public/food?method=getDetail&id=fnb/cate/id/4&page=1&count=50&key=2861010&sig=6c371f25dc46e90d0e4111f82797aa63
                    //get detail cua cac chuyen muc an sang, an chieu
                    $id = $this->_request->getParam("id") == "" ? 1 : $this->_request->getParam("id");
                    $url = static::BASE_URL . $id;

                    $lists = $this->getDetail($url . '/page/' . $page);
                } else if ($method === "getPlaceDetail") {
                    //http://localhost/public/food?method=getPlaceDetail&id=fnb/detail/id/58&page=1&count=50&key=2861010&sig=f7450e9c08977fc117ef4e3b6ac6f02f
                    //get detail cua 1 nha hang
                    $id = $this->_request->getParam("id") == "" ? 1 : $this->_request->getParam("id");
                    $url = static::BASE_URL . $id;

                    $lists = $this->getPlaceDetail($url);
                } else if ($method === "getStarter") {
                    //lay danh sach nha hang noi bat
                    $lists = $this->getStarterRes();
                }

                $returnData = array();
                if ($lists != null && !empty($lists)) {
                    $returnData['errorId'] = Sunny_ErrorHandled::$DONE;
                    $returnData['data'] = $lists;
                    echo json_encode($returnData);
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$PAGE_NOT_FOUND);
                }
            }
        }
    }

    function clearAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        self::$query_cache->clean(Zend_Cache::CLEANING_MODE_ALL);
        echo "clear";
    }

    function getStarterRes() {

        $key = $this->getAccessMemcachedKey();
        if (!$result = self::$query_cache->load($key)) {
            $listStarter = $this->getDetail('http://food.apps.zing.vn/fnb/feature');
            for ($i = 0; $i < count($listStarter); $i++) {
                $listStarter[$i]['images'] = $this->getPlaceImageDetailNoCached(static::BASE_URL . $listStarter[$i]['id']);
            }
            self::$query_cache->save($listStarter, $key);
            return $listStarter;
        } else {
            return $result;
        }
    }

    private function getPlaceImageDetailNoCached($baseUrl) {
        $client = new Zend_Http_Client();
        $client->setUri($baseUrl);
        $response = $client->request();
        $html = $response->getBody();
        $dom = new Zend_Dom_Query($html);
        $results = $dom->query('.food');
        $list = array();
        $index = 0;
        $results->rewind();
        while ($results->valid()) {
            $domDoc = $results->current();
            //Thumbnail image
            $ul = $domDoc->getElementsByTagName("ul");
            for ($i = 0; $i < $ul->length; $i++) {
                $childUl = $ul->item($i);
                if ('food_slider_t' == $childUl->getAttribute('id')) {
                    $childImgTags = $childUl->getElementsByTagName('img');
                    for ($k = 0; $k < $childImgTags->length; $k++) {
                        $list[$k]['images'] = $this->getImageRealPath($childImgTags->item($k)->getAttribute('databig'));
                    }
                    break;
                }
            }
            $index++;
            $results->next();
        }
        return $list;
    }

    function getPlaceDetail($baseUrl) {
        $key = $this->getAccessMemcachedKey();
        if (!$result = self::$query_cache->load($key)) {
            $client = new Zend_Http_Client();
            $client->setUri($baseUrl);
            $response = $client->request();
            $html = $response->getBody();
            $dom = new Zend_Dom_Query($html);
            $results = $dom->query('.food');

            $list = array();
            $index = 0;
            $results->rewind();
            while ($results->valid()) {
                $domDoc = $results->current();

                //Thumbnail image
                $ul = $domDoc->getElementsByTagName("ul");
                for ($i = 0; $i < $ul->length; $i++) {
                    $childUl = $ul->item($i);
                    if ('food_slider_t' == $childUl->getAttribute('id')) {
                        $childImgTags = $childUl->getElementsByTagName('img');

                        for ($k = 0; $k < $childImgTags->length; $k++) {
                            $list['images'][$k] = array(
                                'thumb' => $this->getImageRealPath($childImgTags->item($k)->getAttribute('style')),
                                'image' => $this->getImageRealPath($childImgTags->item($k)->getAttribute('databig'))
                            );
                        }

                        break;
                    }
                }

                $h2 = $domDoc->getElementsByTagName("h2");
                for ($i = 0; $i < $h2->length; $i++) {
                    $h2Child = $h2->item($i);
                    if ('fl' == $h2Child->getAttribute('class')) {
                        $list['name'] = trim($h2Child->nodeValue);
                        break;
                    }
                }

                $div = $domDoc->getElementsByTagName("div");
                for ($i = 0; $i < $div->length; $i++) {
                    $childDiv = $div->item($i);
                    if ('food_rate food_padding7 fr' == $childDiv->getAttribute('class')) {
                        $list['rate'] = $childDiv->getElementsByTagName('span')->length;
                    }
                    if ('restaurant-content' == $childDiv->getAttribute('id')) {
                        $list['content'] = trim($childDiv->nodeValue);
                    }

                    $address = array();
                    //Nha hang tuong tu -right panel
                    if ('food_right fl' == $childDiv->getAttribute('class')) {
                        $mDiv = $childDiv->getElementsByTagName('div');

                        $length = $mDiv->length;
                        $refrencemore = array();
                        $index = 0;
                        for ($i = 0; $i < $length; $i++) {
                            $currentElement = $mDiv->item($i);
                            if ('food_rowleft' == $currentElement->getAttribute('class')) {
                                $a = $currentElement->getElementsByTagName('a');
                                if ($a != null && $a->length > 0) {
                                    $refrencemore[$index]['id'] = $this->getIdFromHref($a->item(0)->getAttribute('href'));
                                }

                                $img = $currentElement->getElementsByTagName('img');
                                if ($img != null && $img->length > 0) {
                                    $refrencemore[$index]['thumb'] = $this->getImageRealPath($img->item(0)->getAttribute('style'));
                                    $refrencemore[$index]['name'] = $img->item(0)->getAttribute('title');
                                }

                                $h3 = $currentElement->getElementsByTagName('span');
                                if ($h3 != null && $h3->length > 0) {
                                    $rateCount = 0;
                                    for ($k = 0; $k < $h3->length; $k++) {
                                        $spanChild = $h3->item($k);
                                        if ('food_imgsprt food_icostar' == $spanChild->getAttribute('class')) {
                                            $rateCount++;
                                        }
                                    }
                                    $refrencemore[$index]['rate'] = $rateCount;
                                }
                                $index++;
                            } else {
                                $class = $currentElement->getAttribute('class');
                                if ('food_map' == $class) {
                                    $list['map'] = $currentElement->getElementsByTagName('iframe')->item(0)->getAttribute('src');
                                } else if ('marbt5' == $class) {//food_inforight
                                    $p = $currentElement->getElementsByTagName('p');
                                    if ($p != null && $p->length > 0) {
                                        $address[count($address)] = trim($currentElement->getElementsByTagName('p')->item(0)->nodeValue);
                                    }
                                }
                            }
                        }

                        $list['refrencemore'] = $refrencemore;
                        $list['address'] = $address;
                        $list['phone'] = array();
                        break;
                    }
                }


                $index++;
                $results->next();
            }
            self::$query_cache->save($list, $key);
            return $list;
        } else {
            return $result;
        }
    }

    function getDetail($baseUrl) {
        $key = $this->getAccessMemcachedKey();
        if (!$result = self::$query_cache->load($key)) {
            $client = new Zend_Http_Client();
            $client->setUri($baseUrl);
            $response = $client->request();
            $html = $response->getBody();
            $dom = new Zend_Dom_Query($html);
            $results = $dom->query('.food_resrow');

            $list = array();
            $index = 0;
            $results->rewind();
            while ($results->valid()) {
                $domDoc = $results->current();
                //http://food.apps.zing.vn/fnb/detail/id/58
                $firstH2 = $domDoc->getElementsByTagName("h2");
//                $list[$index]['detail'] = $firstH2->item(0)->getElementsByTagName("a")->item(0)->getAttribute("href");
                $list[$index]['id'] = $this->getIdFromHref($firstH2->item(0)->getElementsByTagName("a")->item(0)->getAttribute("href"));
                $list[$index]['name'] = trim($firstH2->item(0)->nodeValue);

                $firstImg = $domDoc->getElementsByTagName("img");
                $list[$index]['image'] = $this->getImageRealPath($firstImg->item(0)->getAttribute("style"));
                //xu ly lai image path
//                $firstH = $domDoc->getElementsByTagName("h2");

                $pTag = $domDoc->getElementsByTagName("p");
                $list[$index]['info'] = trim($pTag->item(1)->nodeValue);

                $div = $domDoc->getElementsByTagName("div");
                for ($i = 0; $i < $div->length; $i++) {
                    $childDiv = $div->item($i);
                    if ('food_rate fr' == $childDiv->getAttribute('class')) {
                        $rate = 0;

                        $span = $childDiv->getElementsByTagName('span');
                        for ($k = 0; $k < ($span->length); $k++) {
                            $tmp = $span->item($k);
                            if ($tmp->getAttribute('class') == 'food_imgsprt food_icostar') {
                                $rate++;
                            }
                        }
                        $list[$index]['rate'] = $rate;
                    }
                }
                $index++;
                $results->next();
            }
            self::$query_cache->save($list, $key);
            return $list;
        } else {
            return $result;
        }
    }

    function getList($baseUrl) {
        $key = $this->getAccessMemcachedKey();
        if (!$result = self::$query_cache->load($key)) {
            $client = new Zend_Http_Client();
            $client->setUri($baseUrl);
            $response = $client->request();
            $html = $response->getBody();
            $dom = new Zend_Dom_Query($html);
            $results = $dom->query('.food_menulist');

            $data = array();
            $localIndex = 0;
            $typeIndex = 0;
            $results->rewind();
            $local = array();
            $type = array();

            while ($results->valid()) {
                $domDoc = $results->current();
                $DOMNodeList = $domDoc->getElementsByTagName("div");

                $length = $DOMNodeList->length;
                for ($i = 0; $i < $length; $i++) {
                    $currentDiv = $DOMNodeList->item($i);
                    if ("clr" == $currentDiv->getAttribute("class")) {
                        $childUl = $domDoc->getElementsByTagName("li");
                        $count = $childUl->length;

                        for ($k = 0; $k < $count; $k++) {
                            $childLi = $childUl->item($k);

                            $name = trim($childLi->nodeValue);

                            $href = $childLi->getElementsByTagName("a")->item(0)->getAttribute("href");
                            if (strpos($href, 'local')) {
                                //http://food.apps.zing.vn/fnb/local/id/5
                                $local[$localIndex]['name'] = $name;
                                $local[$localIndex]['id'] = $this->getIdFromHref($href);
                                $localIndex++;
                            } else {
                                //http://food.apps.zing.vn/fnb/cate/id/6
                                $type[$typeIndex]['name'] = $name;
                                $type[$typeIndex]['id'] = $this->getIdFromHref($href);
                                $typeIndex++;
                            }
                        }
                        $data['local'] = $local;
                        $data['cate'] = $type;
                        break;
                    }
                }
                $results->next();
            }
            self::$query_cache->save($data, $key);
            return $data;
        } else {
            return $result;
        }
    }

    private function getIdFromHref($href) {
        return str_replace(static::BASE_URL, "", $href);
    }

}

?>
